/*
 * CEV: sistema open-source para voteções institucionais
 * Copyright (C) 2009, 2010, 2011 Skynet Coders @ Universidade Estadual de Feira de Santana
 *
 * Este arquivo é parte do programa CEV.
 *
 * CEV é um software livre; você pode redistribui-lo e/ou modifica-lo
 * dentro dos termos da Licença Pública Geral GNU (GNU GPL) como publicada
 * pela Fundação do Software Livre (FSF) na versão 3 da Licença.
 *
 * Este programa é distribuido na esperança que possa ser util, mas
 * SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
 * MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para
 * maiores detalhes.
 *
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU
 * junto com este programa, se não, escreva para a Fundação do Software
 * Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QFile>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QtSql/QSqlDatabase>
#include "QVariant"
#include "QVariantList"
#include <QStringList>
#include <QCoreApplication>
#include <QDebug>

#include "usermodel.h"

using namespace std;

/**
  @class UserModel
  @abstract Manipulates the Users table from the CEV Database.
  @package Model
  @author Skynet Coders
  @version 1.0a
  */

UserModel::UserModel()
{
    /* beginning of initialization */
    this->databaseName = QCoreApplication::applicationDirPath() + "/resources/cev.db";
    this->databaseDriver = "QSQLITE";
    this->connectionName = "cev_sqlite";
}

UserModel::~UserModel()
{
    //qDebug("Here");
    //this->closeDatabase();
}

bool UserModel::initialize()
{
    // creating SqlDatabase
    if(!this->connection.isOpen())
    {        
        if(this->connection.connectionName().isNull())
        {
            this->connection = QSqlDatabase::addDatabase(this->databaseDriver, this->connectionName);
            this->connection.setDatabaseName(this->databaseName);
        }
        this->openDatabase();
        return true;
    }
    return false;
    /* end of initialization */
}

/**
  Open a connection to the database.
  @throw
  @return bool
  */
bool UserModel::openDatabase()
{
    try
    {
        if(this->connection.isOpen())
        {
            throw false;
        }
        try
        {
            if(!this->connection.open())
            {
                throw false;
            }
            return true;
        } catch (bool ex)
        {
            qDebug() << this->connection.lastError();
            return false;
        }
    }
    catch (bool ex)
    {
        qDebug("Connection is aready open.");
    }
    return false;
}

/**
  Closes the connection to the database.
  @return bool
  */
bool UserModel::closeDatabase()
{
    try
    {
        if(!this->connection.isOpen())
        {
            throw false;
        }
        this->connection.close();
        QString connection;
        connection = this->connection.connectionName();
        this->connection.~QSqlDatabase();
        return true;
    } catch (bool ex)
    {
        qDebug() << this->connection.lastError();
        return false;
    }
}

bool UserModel::add()
{

    this->initialize();
    QSqlQuery query = QSqlQuery(this->connection);

    QString sql = "insert into users"
            "("
                "name, "
                "registration, "
                "description, "
                "login, "
                "password, "
                "type"
            ")"
            "values "
            "("
                ":name, "
                ":registration,"
                ":description,"
                ":login,"
                ":password,"
                ":type"
            ");";

    query.prepare(sql);
    query.bindValue(":name",this->name);
    query.bindValue(":registration", this->registration);
    query.bindValue(":description",this->description);
    query.bindValue(":login",this->login);
    query.bindValue(":password",this->password);
    query.bindValue(":type",this->type);

    try
    {
        if (!query.exec())
        {
            throw false;
        }
        return true;
    }
    catch (bool ex)
    {
        //qDebug() << this->connection.isOpen();
        //qDebug() << this->closeDatabase();
        throw query.lastError().number();
        return false;
    }
}

/**
  Update data from an specific user.
  @return bool true if data was updated successfuly and false otherwise.
  */
bool UserModel::update()
{
    this->initialize();

    QSqlQuery query = QSqlQuery(this->connection);
    QString sql = "update users set "
            "name = '"+this->name+"', "
            "description = '"+this->description+"', "
            "login = '"+this->login+"', "
            "password = "+this->password+", "
            "type = '"+this->type+"' "
            "where registration = '"+this->registration+"';";

    query.prepare(sql);
    try
    {
        if(!query.exec())
        {
            throw false;
        }
        return true;
    }
    catch (bool err)
    {
        qDebug() << query.lastError();
        throw err;
    }
}

bool UserModel::load(QString registration)
{
    this->initialize();

    QSqlQuery query = QSqlQuery(this->connection);
    QString sql = "select * from users where registration='"+registration+"';";
    query.prepare(sql);
    //qDebug() << sql;

    try
    {
        if(!query.exec())
        {
            throw 1;
        }
        //time to iterate!
        while (query.next())
        {
            this->name = query.value(1).toString();
            this->registration = query.value(2).toString();
            this->description = query.value(3).toString();
            this->login = query.value(4).toString();
            this->password = query.value(5).toString();
//            qDebug() << "nome " + this->name + " | description " + this->description
//                    + " | registration " + this->registration + " | Login " + this->login +
//                    " | password " + this->password;
        }
        if(this->name == "")
        {
            throw 2;
        }
        return true;
    }
    catch (int ex)
    {
        switch(ex)
        {
        case 1:
            qDebug() << query.lastError();
        case 2:
            qDebug("No records with this registration.");
        }
        return false;
    }
}

/**
  Get the private <i>login</i> property.
  @return String
  */
QString UserModel::getLogin()
{
    return this->login;
}

/**
  Get private <i>password</i> property
  @return String
  */
QString UserModel::getPassword()
{
    return this->password;
}

/**
  @abstract Get private <i>registration</i> property
  @return QString
  */
QString UserModel::getRegistration()
{
    return this->registration;
}
/**
  @abstract Set <i>login</i> property.
  @param String login name
  */
void UserModel::setLogin(QString login)
{
    this->login = login;
}

/**
  @abstract Set user's <password> property.
  @param String the password.
  */
void UserModel::setPassword(QString pass)
{
    this->password = pass;
}

/**
  @abstract Set user's <i>registration</i> property.
  @param QString the registration number.
  */
void UserModel::setRegistration(QString registration)
{
    this->registration = registration;
}
